local RenderItem = require("module/render/render_objects/render_item")

local model = class("ModelRenderItem",RenderItem){
    item_type = RENDER_ITEM_VOXEL;
    radian = 0;
    x_scale = 0;
    y_scale = 0;
    bind_model_data = nil,
    spritebatch = nil;
    sprite_indexs = {},
}

function model:__init__(model_data)
    if type(model_data) == "string" then
        self:bind_data(box_core.assets.voxel(model_data))
    else
        self:bind_data(model_data)
    end
end

--[[
        z      y
        l    /
        l  /            坐标系
        l/
        .------- x            
          
         原点
          v
          0---------/l
        /         /  l
      /         /    l
      ----------     l
      ----------     l
      ----------_____l
      ----------    /
      ----------  /  <-- 旋转点位于中心
      ----------/
--]]

function model:bind_data(model_data)
    self.bind_model_data = model_data
    self.spritebatch = love.graphics.newSpriteBatch(model_data.texture,model_data.frame_count)
    for i = 1,model_data.frame_count do
        self.sprite_indexs[i] = self.spritebatch:add(model_data.quads[i])
    end
end

function model:draw(x,y,z,r,xs,ys)
    local camera =  box_core.get_shared("Camera") 
    r,xs,ys = r or 0,xs or 1,ys or 1
    local x,y = camera:toCameraCoords3(x,y,z)
    
    if self.radian ~= r 
        or self.x_scale ~= xs 
        or self.y_scale ~= ys 
        or camera._cam_up_r ~= camera.rotation 
        or camera._cam_up_s ~= camera.scale
    then
        local model_data = self.bind_model_data
        local fx,fy = model_data.frame_width / 2,model_data.frame_height / 2
        for i = 1,model_data.frame_count do
            --[[
                     0---------/0 layer 0
                   /         /  l layer 1
                 /         /    l layer 2
                 ----------     l layer n
                 ----------     l ...
                 ----------_____l  向下叠加
                 ----------    /
                 ----------  / 
                 ----------/
            --]]
            self.spritebatch:set(
                self.sprite_indexs[i],
                model_data.quads[i],
                0,
                (-(i - 1) * ((ys - 1) + camera.scale)),-- <- layer
                r + camera.rotation,
                camera.scale,camera.scale,
                fx,fy
            )
        end

        self.radian = r
        self.x_scale = xs
        self.y_scale = ys
    end

    love.graphics.draw(self.spritebatch,x,y,nil,self.x_scale,self.y_scale)
end

return model